<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <input type="file" name="file">
    <button id="submit">上传</button>
    <script src="https://cdn.bootcss.com/axios/0.19.2/axios.min.js"></script>
    <script>
        function getPrototypeChain(obj) {
            var chain = [];
            while(obj) {
                chain.push(obj);
                obj = Object.getPrototypeOf(obj);
            }
            return chain;
        }
        const file = document.querySelector('input[type=file]');
        const btn = document.querySelector('button');
        

        function getFileType(file) {
            const map = {
                'FFD8FFE0': 'jpg',
                '89504E47': 'png',
                '47494638': 'gif',
                "52494646": 'webp',
                '504b0304': 'xlsx'
            }
            return new Promise(function(resolve, reject) {
                const reader = new FileReader();
                reader.readAsArrayBuffer(file);
                reader.onload = ev => {
                    const array = new Uint8Array(ev.target.result);
                    const key = [...array.slice(0, 4)].map(item => item.toString(16).toUpperCase().padStart(2, '0')).join('');
                    resolve(map[key])
                }
                reader.onerror = ev => {
                    reject()
                }
            })
        }
        btn.onclick = function() {
            getFileType(file.files[0]).then(console.log)
            // console.log()
            // const form = new FormData();
            // console.log(getPrototypeChain(file.files[0]))
            // File 继承至 Blob
            // formData.append('file', file.files[0]);
            // formData.append('name', 'file-test');
            // // type 1
            // axios.post('http://localhost:7787/files', form).then(res => {
            //     console.log(res.data);
            // })
            // // type 2
            // fetch('http://localhost:7787/files', {
            //     method: 'POST',
            //     body: form
            // }).then(res => res.json()).tehn(res => {console.log(res)});
            // // type3
            // var xhr = new XMLHttpRequest();
            // xhr.open('POST', 'http://localhost:7787/files', true);
            // xhr.onload = function () {
            //     console.log(xhr.responseText);
            // };
            // xhr.send(form);
        }
        
    </script>
</body>
</html>